#!/usr/bin/env python3
"""
AIQuant系统流程验证脚本

自动化检查AIQuant系统的流程覆盖情况，验证各个关键业务流程的完整性。
生成详细的验证报告，识别缺失的模块和流程。
"""

import os
import sys
import asyncio
import importlib
import inspect
from pathlib import Path
from typing import Dict, List, Any, Optional, Tuple
from dataclasses import dataclass
from datetime import datetime
import json

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))


@dataclass
class ValidationResult:
    """验证结果数据类"""
    module_name: str
    exists: bool
    has_implementation: bool
    missing_methods: List[str]
    error_message: Optional[str] = None


@dataclass
class FlowValidationResult:
    """流程验证结果数据类"""
    flow_name: str
    is_complete: bool
    completion_percentage: float
    missing_components: List[str]
    existing_components: List[str]
    critical_issues: List[str]


class ProcessValidator:
    """流程验证器"""
    
    def __init__(self):
        self.project_root = project_root
        self.validation_results: Dict[str, ValidationResult] = {}
        self.flow_results: Dict[str, FlowValidationResult] = {}
        
    async def validate_all_processes(self) -> Dict[str, Any]:
        """验证所有流程"""
        print("🔍 开始AIQuant系统流程验证...")
        
        # 1. 验证核心模块
        await self._validate_core_modules()
        
        # 2. 验证业务流程
        await self._validate_business_flows()
        
        # 3. 验证多智能体协作流程
        await self._validate_agent_collaboration_flows()
        
        # 4. 验证系统运行流程
        await self._validate_system_operation_flows()
        
        # 5. 验证用户交互流程
        await self._validate_user_interaction_flows()
        
        # 6. 验证数据流转流程
        await self._validate_data_flow_processes()
        
        # 7. 生成综合报告
        report = await self._generate_validation_report()
        
        return report
    
    async def _validate_core_modules(self):
        """验证核心模块"""
        print("📦 验证核心模块...")
        
        core_modules = {
            'main': 'aiquant.main',
            'workflow_manager': 'aiquant.workflows.workflow_manager',
            'coordination_engine': 'aiquant.coordination.coordination_engine',
            'agent_registry': 'aiquant.agents.agent_registry',
            'data_manager': 'aiquant.data.data_manager',
            'base_agent': 'aiquant.agents.base_agent',
            'agent_roles': 'aiquant.agents.agent_roles'
        }
        
        for module_key, module_path in core_modules.items():
            result = await self._validate_module(module_key, module_path)
            self.validation_results[module_key] = result
            
            status = "✅" if result.exists and result.has_implementation else "❌"
            print(f"  {status} {module_key}: {module_path}")
            if result.error_message:
                print(f"    错误: {result.error_message}")
    
    async def _validate_module(self, module_key: str, module_path: str) -> ValidationResult:
        """验证单个模块"""
        try:
            module = importlib.import_module(module_path)
            
            # 检查模块是否有实际实现
            has_implementation = True
            missing_methods = []
            
            # 获取模块中的类
            classes = [obj for name, obj in inspect.getmembers(module, inspect.isclass)
                      if obj.__module__ == module_path]
            
            if not classes:
                has_implementation = False
                missing_methods.append("No classes found")
            else:
                # 检查关键方法
                for cls in classes:
                    if hasattr(cls, 'initialize') and not self._has_real_implementation(cls.initialize):
                        missing_methods.append(f"{cls.__name__}.initialize")
                    if hasattr(cls, 'close') and not self._has_real_implementation(cls.close):
                        missing_methods.append(f"{cls.__name__}.close")
            
            return ValidationResult(
                module_name=module_path,
                exists=True,
                has_implementation=has_implementation,
                missing_methods=missing_methods
            )
            
        except ImportError as e:
            return ValidationResult(
                module_name=module_path,
                exists=False,
                has_implementation=False,
                missing_methods=[],
                error_message=str(e)
            )
        except Exception as e:
            return ValidationResult(
                module_name=module_path,
                exists=True,
                has_implementation=False,
                missing_methods=[],
                error_message=str(e)
            )
    
    def _has_real_implementation(self, method) -> bool:
        """检查方法是否有真实实现（不只是pass或NotImplemented）"""
        try:
            source = inspect.getsource(method)
            # 简单检查是否只包含pass、NotImplemented或空实现
            lines = [line.strip() for line in source.split('\n') if line.strip()]
            implementation_lines = [line for line in lines 
                                 if not line.startswith(('def ', 'async def ', '#', '"""', "'''"))
                                 and line not in ('pass', 'return', 'return None')]
            return len(implementation_lines) > 0
        except:
            return True  # 如果无法获取源码，假设有实现
    
    async def _validate_business_flows(self):
        """验证核心业务流程"""
        print("💼 验证核心业务流程...")
        
        # 数据获取→处理→存储→分析流程
        data_flow = await self._validate_data_processing_flow()
        self.flow_results['data_processing'] = data_flow
        
        # 策略研发→回测→优化→部署流程
        strategy_flow = await self._validate_strategy_development_flow()
        self.flow_results['strategy_development'] = strategy_flow
        
        # 投资决策→执行→监控→调整流程
        investment_flow = await self._validate_investment_decision_flow()
        self.flow_results['investment_decision'] = investment_flow
    
    async def _validate_data_processing_flow(self) -> FlowValidationResult:
        """验证数据处理流程"""
        components = {
            'data_manager': self.validation_results.get('data_manager', ValidationResult('', False, False, [])),
            'data_adapters': await self._check_path_exists('aiquant/data/adapters'),
            'data_quality': await self._check_method_exists('aiquant.data.data_manager', 'DataManager', 'validate_data'),
            'data_storage': await self._check_method_exists('aiquant.data.data_manager', 'DataManager', 'store_data'),
            'data_analysis': await self._check_method_exists('aiquant.data.data_manager', 'DataManager', 'analyze_data')
        }
        
        existing = [k for k, v in components.items() if v]
        missing = [k for k, v in components.items() if not v]
        completion = len(existing) / len(components) * 100
        
        return FlowValidationResult(
            flow_name="数据处理流程",
            is_complete=completion == 100,
            completion_percentage=completion,
            missing_components=missing,
            existing_components=existing,
            critical_issues=[] if completion > 80 else ["数据处理流程关键组件缺失"]
        )
    
    async def _validate_strategy_development_flow(self) -> FlowValidationResult:
        """验证策略开发流程"""
        components = {
            'strategy_manager': await self._check_path_exists('aiquant/strategies'),
            'backtest_engine': await self._check_path_exists('aiquant/backtest'),
            'strategy_optimizer': await self._check_path_exists('aiquant/optimization'),
            'strategy_deployer': await self._check_path_exists('aiquant/deployment')
        }
        
        existing = [k for k, v in components.items() if v]
        missing = [k for k, v in components.items() if not v]
        completion = len(existing) / len(components) * 100
        
        return FlowValidationResult(
            flow_name="策略开发流程",
            is_complete=completion == 100,
            completion_percentage=completion,
            missing_components=missing,
            existing_components=existing,
            critical_issues=["策略开发核心模块完全缺失"] if completion < 20 else []
        )
    
    async def _validate_investment_decision_flow(self) -> FlowValidationResult:
        """验证投资决策流程"""
        components = {
            'decision_engine': await self._check_path_exists('aiquant/decision'),
            'trade_executor': await self._check_path_exists('aiquant/trading'),
            'position_monitor': await self._check_path_exists('aiquant/monitoring'),
            'portfolio_manager': await self._check_path_exists('aiquant/portfolio')
        }
        
        existing = [k for k, v in components.items() if v]
        missing = [k for k, v in components.items() if not v]
        completion = len(existing) / len(components) * 100
        
        return FlowValidationResult(
            flow_name="投资决策流程",
            is_complete=completion == 100,
            completion_percentage=completion,
            missing_components=missing,
            existing_components=existing,
            critical_issues=["投资决策核心模块完全缺失"] if completion < 20 else []
        )
    
    async def _validate_agent_collaboration_flows(self):
        """验证多智能体协作流程"""
        print("🤖 验证多智能体协作流程...")
        
        # 智能体注册→任务分配→协作执行→结果汇总流程
        agent_flow = await self._validate_agent_lifecycle_flow()
        self.flow_results['agent_lifecycle'] = agent_flow
        
        # 角色权限→协作关系→决策层级流程
        role_flow = await self._validate_role_permission_flow()
        self.flow_results['role_permission'] = role_flow
        
        # 消息传递→事件处理→状态同步流程
        message_flow = await self._validate_message_handling_flow()
        self.flow_results['message_handling'] = message_flow
    
    async def _validate_agent_lifecycle_flow(self) -> FlowValidationResult:
        """验证智能体生命周期流程"""
        components = {
            'agent_registry': self.validation_results.get('agent_registry', ValidationResult('', False, False, [])).exists,
            'task_assignment': await self._check_method_exists('aiquant.agents.agent_registry', 'AgentRegistry', 'assign_task'),
            'coordination_engine': self.validation_results.get('coordination_engine', ValidationResult('', False, False, [])).exists,
            'result_aggregation': await self._check_method_exists('aiquant.coordination.coordination_engine', 'CoordinationEngine', 'summarize_results')
        }
        
        existing = [k for k, v in components.items() if v]
        missing = [k for k, v in components.items() if not v]
        completion = len(existing) / len(components) * 100
        
        return FlowValidationResult(
            flow_name="智能体生命周期流程",
            is_complete=completion == 100,
            completion_percentage=completion,
            missing_components=missing,
            existing_components=existing,
            critical_issues=[] if completion > 70 else ["智能体协作关键组件缺失"]
        )
    
    async def _validate_role_permission_flow(self) -> FlowValidationResult:
        """验证角色权限流程"""
        components = {
            'agent_roles': self.validation_results.get('agent_roles', ValidationResult('', False, False, [])).exists,
            'role_definitions': await self._check_agent_role_completeness(),
            'permission_system': await self._check_method_exists('aiquant.coordination.coordination_engine', 'CoordinationEngine', 'can_agent_handle_task'),
            'hierarchy_management': await self._check_role_hierarchy_exists()
        }
        
        existing = [k for k, v in components.items() if v]
        missing = [k for k, v in components.items() if not v]
        completion = len(existing) / len(components) * 100
        
        return FlowValidationResult(
            flow_name="角色权限流程",
            is_complete=completion == 100,
            completion_percentage=completion,
            missing_components=missing,
            existing_components=existing,
            critical_issues=["角色配置不完整"] if completion < 60 else []
        )
    
    async def _validate_message_handling_flow(self) -> FlowValidationResult:
        """验证消息处理流程"""
        components = {
            'message_passing': await self._check_method_exists('aiquant.agents.agent_registry', 'AgentRegistry', 'send_message'),
            'event_bus': await self._check_path_exists('aiquant/events'),
            'state_sync': await self._check_method_exists('aiquant.agents.agent_registry', 'AgentRegistry', 'get_agent_status'),
            'message_queue': await self._check_method_exists('aiquant.agents.agent_registry', 'AgentRegistry', 'get_messages_for_agent')
        }
        
        existing = [k for k, v in components.items() if v]
        missing = [k for k, v in components.items() if not v]
        completion = len(existing) / len(components) * 100
        
        return FlowValidationResult(
            flow_name="消息处理流程",
            is_complete=completion == 100,
            completion_percentage=completion,
            missing_components=missing,
            existing_components=existing,
            critical_issues=["事件驱动机制缺失"] if 'event_bus' in missing else []
        )
    
    async def _validate_system_operation_flows(self):
        """验证系统运行流程"""
        print("⚙️ 验证系统运行流程...")
        
        # 系统启动→初始化→运行→关闭流程
        startup_flow = await self._validate_system_startup_flow()
        self.flow_results['system_startup'] = startup_flow
        
        # 健康检查→监控→告警→恢复流程
        monitoring_flow = await self._validate_monitoring_flow()
        self.flow_results['monitoring'] = monitoring_flow
        
        # 配置管理→热更新→版本控制流程
        config_flow = await self._validate_configuration_flow()
        self.flow_results['configuration'] = config_flow
    
    async def _validate_system_startup_flow(self) -> FlowValidationResult:
        """验证系统启动流程"""
        components = {
            'main_application': self.validation_results.get('main', ValidationResult('', False, False, [])).exists,
            'component_initialization': await self._check_method_exists('aiquant.main', 'AIQuantSystem', 'initialize'),
            'health_check': await self._check_method_exists('aiquant.main', 'AIQuantSystem', 'check_health'),
            'graceful_shutdown': await self._check_method_exists('aiquant.main', 'AIQuantSystem', 'close')
        }
        
        existing = [k for k, v in components.items() if v]
        missing = [k for k, v in components.items() if not v]
        completion = len(existing) / len(components) * 100
        
        return FlowValidationResult(
            flow_name="系统启动流程",
            is_complete=completion == 100,
            completion_percentage=completion,
            missing_components=missing,
            existing_components=existing,
            critical_issues=[] if completion > 80 else ["系统生命周期管理不完整"]
        )
    
    async def _validate_monitoring_flow(self) -> FlowValidationResult:
        """验证监控流程"""
        components = {
            'health_checks': await self._check_method_exists('aiquant.data.data_manager', 'DataManager', 'check_health'),
            'system_metrics': await self._check_method_exists('aiquant.main', 'AIQuantSystem', 'get_system_metrics'),
            'alert_manager': await self._check_path_exists('aiquant/monitoring/alerts'),
            'auto_recovery': await self._check_path_exists('aiquant/monitoring/recovery')
        }
        
        existing = [k for k, v in components.items() if v]
        missing = [k for k, v in components.items() if not v]
        completion = len(existing) / len(components) * 100
        
        return FlowValidationResult(
            flow_name="监控流程",
            is_complete=completion == 100,
            completion_percentage=completion,
            missing_components=missing,
            existing_components=existing,
            critical_issues=["监控告警机制缺失"] if completion < 50 else []
        )
    
    async def _validate_configuration_flow(self) -> FlowValidationResult:
        """验证配置管理流程"""
        components = {
            'config_manager': await self._check_path_exists('aiquant/config'),
            'hot_reload': await self._check_path_exists('aiquant/config/hot_reload'),
            'version_control': await self._check_path_exists('aiquant/config/versions'),
            'environment_config': await self._check_path_exists('config')
        }
        
        existing = [k for k, v in components.items() if v]
        missing = [k for k, v in components.items() if not v]
        completion = len(existing) / len(components) * 100
        
        return FlowValidationResult(
            flow_name="配置管理流程",
            is_complete=completion == 100,
            completion_percentage=completion,
            missing_components=missing,
            existing_components=existing,
            critical_issues=["配置管理系统完全缺失"] if completion < 20 else []
        )
    
    async def _validate_user_interaction_flows(self):
        """验证用户交互流程"""
        print("👤 验证用户交互流程...")
        
        # 用户认证→权限验证→操作授权流程
        auth_flow = await self._validate_authentication_flow()
        self.flow_results['authentication'] = auth_flow
        
        # 请求处理→业务逻辑→响应返回流程
        api_flow = await self._validate_api_processing_flow()
        self.flow_results['api_processing'] = api_flow
        
        # 错误处理→日志记录→用户反馈流程
        error_flow = await self._validate_error_handling_flow()
        self.flow_results['error_handling'] = error_flow
    
    async def _validate_authentication_flow(self) -> FlowValidationResult:
        """验证认证流程"""
        components = {
            'auth_manager': await self._check_path_exists('aiquant/auth'),
            'permission_manager': await self._check_path_exists('aiquant/auth/permissions'),
            'session_manager': await self._check_path_exists('aiquant/auth/sessions'),
            'security_audit': await self._check_path_exists('aiquant/auth/audit')
        }
        
        existing = [k for k, v in components.items() if v]
        missing = [k for k, v in components.items() if not v]
        completion = len(existing) / len(components) * 100
        
        return FlowValidationResult(
            flow_name="认证流程",
            is_complete=completion == 100,
            completion_percentage=completion,
            missing_components=missing,
            existing_components=existing,
            critical_issues=["安全认证系统完全缺失"] if completion < 20 else []
        )
    
    async def _validate_api_processing_flow(self) -> FlowValidationResult:
        """验证API处理流程"""
        components = {
            'api_framework': await self._check_path_exists('aiquant/api'),
            'request_handlers': await self._check_api_handlers_exist(),
            'business_logic': await self._check_business_logic_exists(),
            'response_formatting': await self._check_response_formatters_exist()
        }
        
        existing = [k for k, v in components.items() if v]
        missing = [k for k, v in components.items() if not v]
        completion = len(existing) / len(components) * 100
        
        return FlowValidationResult(
            flow_name="API处理流程",
            is_complete=completion == 100,
            completion_percentage=completion,
            missing_components=missing,
            existing_components=existing,
            critical_issues=[] if completion > 60 else ["API业务逻辑实现不完整"]
        )
    
    async def _validate_error_handling_flow(self) -> FlowValidationResult:
        """验证错误处理流程"""
        components = {
            'exception_handling': await self._check_exception_handlers_exist(),
            'logging_system': await self._check_logging_system_exists(),
            'user_feedback': await self._check_user_feedback_system_exists(),
            'error_recovery': await self._check_error_recovery_exists()
        }
        
        existing = [k for k, v in components.items() if v]
        missing = [k for k, v in components.items() if not v]
        completion = len(existing) / len(components) * 100
        
        return FlowValidationResult(
            flow_name="错误处理流程",
            is_complete=completion == 100,
            completion_percentage=completion,
            missing_components=missing,
            existing_components=existing,
            critical_issues=[] if completion > 70 else ["错误处理机制不完整"]
        )
    
    async def _validate_data_flow_processes(self):
        """验证数据流转流程"""
        print("📊 验证数据流转流程...")
        
        # 数据采集→清洗→验证→存储流程（已在业务流程中验证）
        
        # 数据查询→处理→分析→输出流程
        query_flow = await self._validate_data_query_flow()
        self.flow_results['data_query'] = query_flow
        
        # 数据同步→备份→恢复→归档流程
        backup_flow = await self._validate_data_backup_flow()
        self.flow_results['data_backup'] = backup_flow
    
    async def _validate_data_query_flow(self) -> FlowValidationResult:
        """验证数据查询流程"""
        components = {
            'query_interface': await self._check_method_exists('aiquant.data.data_manager', 'DataManager', 'query_data'),
            'data_processing': await self._check_method_exists('aiquant.data.data_manager', 'DataManager', 'process_data'),
            'data_analysis': await self._check_method_exists('aiquant.data.data_manager', 'DataManager', 'analyze_data'),
            'data_export': await self._check_method_exists('aiquant.data.data_manager', 'DataManager', 'export_data')
        }
        
        existing = [k for k, v in components.items() if v]
        missing = [k for k, v in components.items() if not v]
        completion = len(existing) / len(components) * 100
        
        return FlowValidationResult(
            flow_name="数据查询流程",
            is_complete=completion == 100,
            completion_percentage=completion,
            missing_components=missing,
            existing_components=existing,
            critical_issues=[] if completion > 70 else ["数据查询处理链不完整"]
        )
    
    async def _validate_data_backup_flow(self) -> FlowValidationResult:
        """验证数据备份流程"""
        components = {
            'data_sync': await self._check_path_exists('aiquant/data/sync'),
            'backup_manager': await self._check_path_exists('aiquant/data/backup'),
            'recovery_manager': await self._check_path_exists('aiquant/data/recovery'),
            'archive_manager': await self._check_path_exists('aiquant/data/archive')
        }
        
        existing = [k for k, v in components.items() if v]
        missing = [k for k, v in components.items() if not v]
        completion = len(existing) / len(components) * 100
        
        return FlowValidationResult(
            flow_name="数据备份流程",
            is_complete=completion == 100,
            completion_percentage=completion,
            missing_components=missing,
            existing_components=existing,
            critical_issues=["数据备份恢复系统完全缺失"] if completion < 20 else []
        )
    
    # 辅助方法
    async def _check_path_exists(self, path: str) -> bool:
        """检查路径是否存在"""
        full_path = self.project_root / path
        return full_path.exists()
    
    async def _check_method_exists(self, module_path: str, class_name: str, method_name: str) -> bool:
        """检查方法是否存在"""
        try:
            module = importlib.import_module(module_path)
            cls = getattr(module, class_name, None)
            if cls is None:
                return False
            return hasattr(cls, method_name)
        except:
            return False
    
    async def _check_agent_role_completeness(self) -> bool:
        """检查智能体角色配置完整性"""
        try:
            # 尝试导入角色配置，如果不存在则返回False
            import aiquant.agents.agent_roles as roles_module
            # 检查模块中是否有角色定义
            role_attrs = [attr for attr in dir(roles_module) if not attr.startswith('_')]
            return len(role_attrs) > 10  # 期望有较多角色配置
        except ImportError:
            return False
        except Exception:
            return False
    
    async def _check_role_hierarchy_exists(self) -> bool:
        """检查角色层级是否存在"""
        try:
            from aiquant.agents.agent_roles import AgentLevel
            return hasattr(AgentLevel, 'EXECUTIVE')
        except:
            return False
    
    async def _check_api_handlers_exist(self) -> bool:
        """检查API处理器是否存在"""
        api_path = self.project_root / 'aiquant' / 'api'
        if not api_path.exists():
            return False
        
        # 检查是否有路由文件
        route_files = list(api_path.glob('*_routes.py'))
        return len(route_files) > 0
    
    async def _check_business_logic_exists(self) -> bool:
        """检查业务逻辑是否存在"""
        # 检查是否有业务逻辑模块
        business_paths = [
            'aiquant/strategies',
            'aiquant/trading',
            'aiquant/portfolio',
            'aiquant/risk'
        ]
        
        for path in business_paths:
            if await self._check_path_exists(path):
                return True
        return False
    
    async def _check_response_formatters_exist(self) -> bool:
        """检查响应格式化器是否存在"""
        return await self._check_path_exists('aiquant/api/formatters')
    
    async def _check_exception_handlers_exist(self) -> bool:
        """检查异常处理器是否存在"""
        return await self._check_path_exists('aiquant/exceptions')
    
    async def _check_logging_system_exists(self) -> bool:
        """检查日志系统是否存在"""
        try:
            # 检查是否使用了loguru或其他日志系统
            import importlib
            try:
                importlib.import_module('loguru')
                return True
            except ImportError:
                # 检查标准logging模块
                import logging
                return True
        except Exception:
            return False
    
    async def _check_user_feedback_system_exists(self) -> bool:
        """检查用户反馈系统是否存在"""
        return await self._check_path_exists('aiquant/feedback')
    
    async def _check_error_recovery_exists(self) -> bool:
        """检查错误恢复机制是否存在"""
        return await self._check_path_exists('aiquant/recovery')
    
    async def _generate_validation_report(self) -> Dict[str, Any]:
        """生成验证报告"""
        print("📋 生成验证报告...")
        
        # 计算总体统计
        total_flows = len(self.flow_results)
        complete_flows = sum(1 for flow in self.flow_results.values() if flow.is_complete)
        avg_completion = sum(flow.completion_percentage for flow in self.flow_results.values()) / total_flows if total_flows > 0 else 0
        
        # 收集关键问题
        critical_issues = []
        for flow in self.flow_results.values():
            critical_issues.extend(flow.critical_issues)
        
        # 收集缺失模块
        missing_modules = []
        for result in self.validation_results.values():
            if not result.exists:
                missing_modules.append(result.module_name)
        
        report = {
            'validation_timestamp': datetime.now().isoformat(),
            'summary': {
                'total_flows_checked': total_flows,
                'complete_flows': complete_flows,
                'incomplete_flows': total_flows - complete_flows,
                'average_completion_percentage': round(avg_completion, 2),
                'overall_status': 'GOOD' if avg_completion > 70 else 'NEEDS_IMPROVEMENT' if avg_completion > 40 else 'CRITICAL'
            },
            'module_validation': {
                name: {
                    'exists': result.exists,
                    'has_implementation': result.has_implementation,
                    'missing_methods': result.missing_methods,
                    'error_message': result.error_message
                } for name, result in self.validation_results.items()
            },
            'flow_validation': {
                name: {
                    'is_complete': flow.is_complete,
                    'completion_percentage': flow.completion_percentage,
                    'missing_components': flow.missing_components,
                    'existing_components': flow.existing_components,
                    'critical_issues': flow.critical_issues
                } for name, flow in self.flow_results.items()
            },
            'critical_issues': critical_issues,
            'missing_modules': missing_modules,
            'recommendations': self._generate_recommendations()
        }
        
        return report
    
    def _generate_recommendations(self) -> List[str]:
        """生成改进建议"""
        recommendations = []
        
        # 基于验证结果生成建议
        for name, flow in self.flow_results.items():
            if flow.completion_percentage < 50:
                recommendations.append(f"优先实现{flow.flow_name}的缺失组件: {', '.join(flow.missing_components)}")
            elif flow.critical_issues:
                recommendations.append(f"解决{flow.flow_name}的关键问题: {', '.join(flow.critical_issues)}")
        
        # 通用建议
        if any(not result.exists for result in self.validation_results.values()):
            recommendations.append("补充缺失的核心模块实现")
        
        if any('strategy' in name for name in self.flow_results.keys() if not self.flow_results[name].is_complete):
            recommendations.append("优先实现策略开发和回测相关模块")
        
        if any('auth' in name for name in self.flow_results.keys() if not self.flow_results[name].is_complete):
            recommendations.append("实现安全认证和权限控制系统")
        
        return recommendations


async def main():
    """主函数"""
    validator = ProcessValidator()
    
    try:
        # 执行验证
        report = await validator.validate_all_processes()
        
        # 打印摘要
        print("\n" + "="*60)
        print("🎯 AIQuant系统流程验证报告摘要")
        print("="*60)
        
        summary = report['summary']
        print(f"📊 总体状态: {summary['overall_status']}")
        print(f"📈 平均完成度: {summary['average_completion_percentage']:.1f}%")
        print(f"✅ 完整流程: {summary['complete_flows']}/{summary['total_flows_checked']}")
        print(f"❌ 不完整流程: {summary['incomplete_flows']}")
        
        # 打印关键问题
        if report['critical_issues']:
            print(f"\n🚨 关键问题 ({len(report['critical_issues'])}个):")
            for issue in report['critical_issues'][:5]:  # 只显示前5个
                print(f"  • {issue}")
        
        # 打印缺失模块
        if report['missing_modules']:
            print(f"\n📦 缺失模块 ({len(report['missing_modules'])}个):")
            for module in report['missing_modules'][:5]:  # 只显示前5个
                print(f"  • {module}")
        
        # 打印建议
        if report['recommendations']:
            print(f"\n💡 改进建议 ({len(report['recommendations'])}个):")
            for rec in report['recommendations'][:5]:  # 只显示前5个
                print(f"  • {rec}")
        
        # 保存详细报告
        report_file = validator.project_root / 'validation_report.json'
        with open(report_file, 'w', encoding='utf-8') as f:
            json.dump(report, f, ensure_ascii=False, indent=2)
        
        print(f"\n📄 详细报告已保存到: {report_file}")
        print("="*60)
        
        return report
        
    except Exception as e:
        print(f"❌ 验证过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
        return None


if __name__ == "__main__":
    asyncio.run(main())